package so.shanku.essential.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.senab.photoview.PhotoViewAttacher;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.utils.Constant;

import java.util.List;

public class ShowBigImageActivity extends BaseActivity {
    private static final String STATE_POSITION = "STATE_POSITION";

    @ViewInject(id = R.id.pager)
    private ViewPager mPager;
    @ViewInject(id = R.id.view_ind_layout)
    LinearLayout view_ind_layout;     //指示器
    /**
     * 传过来的图片位置
     */
    private int position;
    /**
     * 传过来的图片信息
     */
    private List<JsonMap<String, Object>> data_imageList;
    /**
     * 返回键
     */
    @ViewInject(id = R.id.back)
    private TextView back;

    @ViewInject(id = R.id.indicator)
    private TextView indicator;


    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // flag = 1 ;
        setContentView(R.layout.show_bigimage_activity);
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra(Constant.BUNDLE_EXTRA);
//		data_imageList = (List<JsonMap<String, Object>>) intent.getBundleExtra(
//				ExtraKeys.Key_Msg3).getSerializable(ExtraKeys.Key_Msg1);
        position = bundle.getInt(Constant.IMAGE_POSITION);
        String map = bundle.getString(Constant.IMAGE_JSON_STR);
        data_imageList = JsonParseHelper.getList_JsonMap(map);

        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ImagePagerAdapter mAdapter = new ImagePagerAdapter(
                getSupportFragmentManager());
        mPager.setAdapter(mAdapter);


        CharSequence text = getString(R.string.viewpager_indicator, 1, mPager
                .getAdapter().getCount());
        indicator.setText(text);
        // 更新下标
        mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageSelected(int arg0) {
                CharSequence text = getString(R.string.viewpager_indicator,
                        arg0 + 1, data_imageList.size());
                indicator.setText(text);
            }

        });
        if (savedInstanceState != null) {
            position = savedInstanceState.getInt(STATE_POSITION);
        }

        mPager.setCurrentItem(position);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_POSITION, mPager.getCurrentItem());
    }

    private class ImagePagerAdapter extends FragmentStatePagerAdapter {


        public ImagePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return data_imageList == null ? 0 : data_imageList.size();
        }

        @Override
        public Fragment getItem(int position) {
            return ImageDetailFragment.newInstance(data_imageList.get(position).getStringNoNull("Path"));
        }

    }

    public static final class ImageDetailFragment extends Fragment {
        private String mImageUrl;
        private ImageView mImageView;
        private ProgressBar progressBar;
        private PhotoViewAttacher mAttacher;

        public static ImageDetailFragment newInstance(String imageUrl) {
            final ImageDetailFragment f = new ImageDetailFragment();

            final Bundle args = new Bundle();
            args.putString("url", imageUrl);
            f.setArguments(args);

            return f;
        }

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mImageUrl = getArguments() != null ? getArguments().getString("url") : null;

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            final View v = inflater.inflate(R.layout.show_big_image_item, container, false);
            mImageView = (ImageView) v.findViewById(R.id.image);
            mAttacher = new PhotoViewAttacher(mImageView);

            mAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {

                @Override
                public void onPhotoTap(View arg0, float arg1, float arg2) {
                    getActivity().finish();
                }
            });

            progressBar = (ProgressBar) v.findViewById(R.id.loading);
            return v;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
//            if (MyApplication.getInstance().getBitmapHashMap().containsKey(mImageUrl)) {
//                progressBar.setVisibility(View.GONE);
//                mImageView.setImageBitmap(MyApplication.getInstance().getBitmapHashMap().get(mImageUrl));
//            } else {
                ImageLoader.getInstance().displayImage(mImageUrl, mImageView, new ImageLoadingListener() {
                    @Override
                    public void onLoadingStarted(String imageUri, View view) {
                        progressBar.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                        String message = null;
                        switch (failReason.getType()) {
                            case IO_ERROR:
                                message = getString(R.string.download_error);
                                break;
                            case DECODING_ERROR:
                                message = getString(R.string.images_cannot_be_displayed);
                                break;
                            case NETWORK_DENIED:
                                message = getString(R.string.network_problems_can_not_download);
                                break;
                            case OUT_OF_MEMORY:
                                message = getString(R.string.the_picture_is_too_big_to_show);
                                break;
                            case UNKNOWN:
                                message = getString(R.string.unknown_error);
                                break;
                        }
                        Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                        progressBar.setVisibility(View.GONE);
                        mAttacher.update();
                    }

                    @Override
                    public void onLoadingCancelled(String s, View view) {
                        progressBar.setVisibility(View.GONE);
                    }
                });
            //}


        }

    }

}

